package com.daoshu.mds.system.component;
import com.alibaba.fastjson.JSON;
import com.daoshu.mds.system.service.IAccountService;
import com.daoshu.system.bo.AccountBo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

/**
 * redis数据过期监听器*/
@Component
@Slf4j
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

	@Autowired
	@Lazy
	private IAccountService accountService;

    /**
     * Creates new {@link MessageListener} for {@code __keyevent@*__:expired} messages.
     *
     * @param listenerContainer must not be {@literal null}.
     */
    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * 针对redis数据失效事件，进行数据处理
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
    	String key = message.toString();
    	log.debug("redis键过期，过期的键是:{}",key);
    	if(key.startsWith("AGENT")||key.startsWith("MOBILE")) {
    		byte[] bytes = message.getBody();
    		AccountBo bo = JSON.parseObject(bytes, AccountBo.class );
    		accountService.logout(bo);
    	}
    	
    }
    
}